package com.bemyapp.mp;

import java.io.IOException;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;

public class MP {

	static private MediaPlayer instance;
	
	private MP(){
		instance = new MediaPlayer();
	}
	
	static public MediaPlayer getInstance(){
		if (instance == null) {
			new MP();
		}
		return instance;
	}
	
	static public void volumeUp(Context c, int canal){
		AudioManager am = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
		am.adjustStreamVolume(canal, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
	}
	
	static public void volumeDown(Context c, int canal){
		AudioManager am = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
		am.adjustStreamVolume(canal, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
	}
	
	static public void play(String pathToFile, Context context){
			android.media.MediaPlayer mp = getInstance();
			AssetFileDescriptor musicFileDescriptor;
			try {
			
			musicFileDescriptor = context.getAssets().openFd(pathToFile);
			
			mp.reset();
			mp.setDataSource(musicFileDescriptor.getFileDescriptor(), musicFileDescriptor.getStartOffset(), musicFileDescriptor.getLength());
			musicFileDescriptor.close();//Don't forget to close, the documentation of setDataSource is very specific about it

			mp.setOnPreparedListener(new OnPreparedListener() {
			    public void onPrepared(MediaPlayer mp) {
			        mp.start();
			    }
			});
			mp.prepareAsync();
			
			
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	static public void release(){
		if (instance != null){
			instance.release();
		}
	}
	
	static public void pause(){
		if (instance != null){
			instance.pause();
		}
	}
	
}
